<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Mensajes
 *
 * @author Virtualidad
 * @export Modules
 * @export-metadata RequiredRoles:ROLE_STUDENT:ROLE_PROFESSOR:ROLE_DIRECTIVE
 */
class Mensajes extends Module {

    private $emails = array();
    private $subject = "";
    private $message = "";

    /**
     * @export-metadata Bind:this
     */
    public function compose() {
        $config = ModulesContext::instance()->getConfig();

        $this->assign("emails", $this->processEmails($this->emails));
        $this->assign("action", $this->route->action("send"));
        $this->assign("cancel", $this->route->appAction($config->DefaultApp, $config->DefaultModule));

        $this->display("compose");
    }

    public function index() {
        $this->compose();
    }

    /**
     * @export-metadata Bind:this
     */
    public function send() {
        if ($this->request->submitted()) {
            $enviado = false;

            if (is_array($this->emails) && count($this->emails) > 0) {
                $enviado = $this->model->contacts->EnviarEmailEstudiante($this->message, $this->subject, $this->emails);
            }

            if ($enviado == true) {
                $this->addMessage(new Message("Mensaje enviado con &eacute;xito.", "", Message::SUCCESS));
                $this->emails = array();
            } else {
                $this->addMessage(new Message("No se pudo enviar el mensaje.", "Ups", Message::WARNING));
            }
        }
        $this->compose();
    }

    public function getEmails() {
        return $this->emails;
    }

    public function setEmails($emails) {
        $this->emails = $emails;
    }

    public function getSubject() {
        return $this->subject;
    }

    public function setSubject($subject) {
        $this->subject = $subject;
    }

    public function getMessage() {
        return $this->message;
    }

    public function setMessage($message) {
        $this->message = $message;
    }

    private function processEmails(&$emails) {
        $result = array();

        if (is_array($emails)) {
            foreach ($emails as $email) {
                $splitted = explode(" ", $email, 2);
                $result[] = $splitted;
            }
        }

        return $result;
    }

}

?>
